package test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class MyThread extends Thread{
        private String name;
        private File sourceFile;
        private File targetDir;
        private long begin;
        private long end;
        public MyThread(String name, File sourceFile, File targetDir, long begin, long end) {
            this.name = name;
            this.sourceFile = sourceFile;
            this.targetDir = targetDir;
            this.begin = begin;
            this.end = end;
        }
        @Override
        public void run() {
            //定义读写的文件访问流
            RandomAccessFile rafRead = null;
            RandomAccessFile rafWrite = null;
            try {
                rafRead = new RandomAccessFile(sourceFile, "r");
                rafWrite = new RandomAccessFile(targetDir, "rw");
                //设置文件指针的开始位置和文件长度
                rafWrite.setLength(end);
                rafRead.seek(begin);
                rafWrite.seek(begin);
                int buffSize = 1024*6;
                byte[] buff = new byte[buffSize];
                while((begin+buffSize)<=end){
                    //把数据读入到buff缓冲数组中
                    rafRead.read(buff);
                    //把buff缓冲数组的数据写入到目标文件
                    rafWrite.write(buff);
                    //起始位置再向前移
                    begin+=buffSize;
                }
                //begin+buffSize超出了每一段的结尾，最后那一撮另外读
                long lastSize = end-begin;
                rafRead.read(buff, 0, (int) lastSize);
                rafWrite.write(buff, 0, (int) lastSize);
                System.out.println(this.name+"拷贝完成!");
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                IOUtils.closeRandomAccessFile(rafRead);
                IOUtils.closeRandomAccessFile(rafWrite);
            }
        }
    }
